<template>
  <div class="chart-container">
    <div ref="competitionChart" class="chart"></div>
    <div ref="awardChart" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getCompetition} from '@/api/table'

export default {

  data() {
    return {
      competitionData:[],
      competitionChart: null,
      awardChart: null,
      queryParams:{
        pageNum:1,
        pageSize:4000,
      },
    };
  },
  computed: {
    processedCompetitionData() {
      const competitionMap = new Map();
      this.competitionData.forEach(item => {
        const comp = competitionMap.get(item.competitionId) || {
          total: 0,
          winners: 0
        };
        comp.total++;
        if (item.award === 1) comp.winners++;
        competitionMap.set(item.competitionId, comp);
      });

      // 增加过滤条件
      return Array.from(competitionMap)
        .filter(([id, data]) => data.total >= 10) // 过滤参赛人数不足10的竞赛
        .map(([id, data]) => ({
          id,
          rate: (data.winners / (data.total+1000) * 100).toFixed(2)    //全部人数在这里
        }));
    },
    processedAwardData() {
      // 获取有效竞赛ID集合
      const validCompetitions = new Set(
        this.processedCompetitionData.map(item => item.id)
      );

      // 只统计有效竞赛的奖项
      const awardCount = {};
      this.competitionData
        .filter(item =>
          item.award === 1 &&
          item.awards &&
          validCompetitions.has(item.competitionId)
        )
        .forEach(item => {
          awardCount[item.awards] = (awardCount[item.awards] || 0) + 1;
        });

      return Object.entries(awardCount).map(([name, value]) => ({
        name,
        value
      }));

    }
  },
  mounted() {
    this.fetchData();

    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
    if (this.competitionChart) this.competitionChart.dispose();
    if (this.awardChart) this.awardChart.dispose();
  },
  methods: {
    // 获取后端数据
    async fetchData() {
      try {
        const res = await getCompetition(this.queryParams); // 直接 await
        console.log('API响应数据:', res.data.rows);
        // 确保数据结构正确
        if (res && res.data) {
          this.competitionData = res.data.rows;
          this.initCharts();
        } else {
          throw new Error('响应数据格式错误');
        }
      } catch (error) {
        console.error('数据加载失败:', error);
      }
    },
    initCharts() {
      this.initCompetitionChart();
      this.initAwardChart();
    },
    initCompetitionChart() {
      this.competitionChart = echarts.init(this.$refs.competitionChart);
      const option = {
        title: { text: '各竞赛获奖率' },
        tooltip: {
          formatter: '{b}<br/>获奖率: {c}%'
        },
        xAxis: {
          type: 'category',
          data: this.processedCompetitionData.map(item => `竞赛 ${item.id}`)
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [{
          data: this.processedCompetitionData.map(item => item.rate),
          type: 'bar',
          itemStyle: {
            color: '#5470C6'
          }
        }]
      };
      this.competitionChart.setOption(option);
    },
    initAwardChart() {
      this.awardChart = echarts.init(this.$refs.awardChart);
      const option = {
        title: { text: '奖项分布' },
        tooltip: {
          formatter: '{b}: {d}%'
        },
        series: [{
          type: 'pie',
          radius: '50%',
          data: this.processedAwardData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      this.awardChart.setOption(option);
    },
    handleResize() {
      if (this.competitionChart) this.competitionChart.resize();
      if (this.awardChart) this.awardChart.resize();
    }
  },
  watch: {
    competitionData: {
      handler() {
        this.initCharts();
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.chart-container {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.chart {
  width: 600px;
  height: 400px;
  margin: 20px;
}
</style>
